<template>
  <div id="categories">
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>商品列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图card -->
<el-card class="box-card">
      <el-button type="primary" class="btn" @click="insertCategories">添加分类</el-button>
  <!-- 表格区 -->
  <!-- 分类名称字段需要安装第三方依赖 npm i vue-table-with-tree-grid -S -->
  	<tree-table
    class="tree-table"
  		index-text="#"
  		show-index
  		stripe
  		border
  		:data="catelist"
  		:columns="columns"
  		:expand-type="false"
  		:selection-type="false"
  	  >
  		<template slot="isok" slot-scope="scope">
  		  <i class="el-icon-success" v-if="scope.row.cat_deleted ===false" style="color: lightGreen"></i>
  		  <i class="el-icon-error" v-else style="color: red"></i>
  		</template>
  		<template slot="order" slot-scope="scope">
  		   <el-tag type="primary" effect="plain" size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
  		   <el-tag type="success" effect="plain" size="mini" v-else-if="scope.row.cat_level === 1">二级</el-tag>
  		   <el-tag type="warning" effect="plain" size="mini" v-else>三级</el-tag>
  		</template>
  		<template slot="opt" slot-scope="scope">
  			<el-button type="primary" icon="el-icon-edit" size="mini" @click="editCate(scope.row)">编辑</el-button>
  			<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row)">删除</el-button>
  		</template>
  	  </tree-table>
<!-- 分页区 -->
 <div style="margin-top:15px">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="querInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="querInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
   <!-- 弹出添加分类对话框 -->
<el-dialog title="添加分类" :visible.sync="dialogCate" @close='addCateDialog'>
  <el-form :model="addCateForm" class="demo-ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="分类名称：" prop="cat_name">
      <el-input v-model="addCateForm.cat_name" style="width:36%"></el-input>
    </el-form-item>
    <el-form-item label="父级分类：" prop="">
       <el-cascader
       change-on-select
       clearable
    v-model="selectKeys"
    expand-trigger="hover"
    :options="parentCateList"
    :props="expandTrigger"
    @change="handleChange"></el-cascader>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offForm">取 消</el-button>
    <el-button type="primary" @click="sureForm">确 定</el-button>
  </div>
</el-dialog>
 <!-- 弹出编辑分类对话框 -->
<el-dialog title="编辑分类" :visible.sync="editDialogCate">
  <el-form :model="editForm" class="demo-ruleForm" :rules="rules" ref="ruleFormEdit" label-width="100px">
    <el-form-item label="分类名称：" prop="cat_name">
      <el-input v-model="editForm.cat_name" style="width:36%"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editOffForm">取 消</el-button>
    <el-button type="primary" @click="editSureForm">确 定</el-button>
  </div>
</el-dialog>
</el-card>
  </div>
</template>
<script>
export default {
  data(){
    return{
      catelist:[],
      // prop对应接口
      columns: [
        { label: "分类名称", prop: "cat_name" },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
  	],
  	props: {
  		expandType: false,
  		selectionType: false,
  	  },
      //接口type等于3代表显示3级分类  不传递代表获取所有
      querInfo:{
        type:3,
        pagenum:1,
        pagesize:5
      },
      total:0,
      dialogCate:false,
      editDialogCate:false,
      addCateForm:{
        cat_name:'',
        //0代表父级分类的id
        cat_pid:0,
        //0代表一级分类
        cat_level:0
      },
      rules:{
          cat_name:[
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
        },
        //获取父级的列表数据
        parentCateList:[],
        expandTrigger:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
        },
        selectKeys:[],
        editForm:{}
    }
  },
  created(){
    //获取商品分类
    this.cateList()
  },
  methods:{
    async cateList(){
      const {data:res}=await this.$http.get('categories',{params:this.querInfo})
      if(res.meta.status!==200){
        return this.$message.error('获取商品列表失败');
      }
      // console.log(res);
      this.catelist=res.data.result
      this.total=res.data.total
    },
    //查询商品
    getShop(){},
    //添加分类
    insertCategories(){
      this.getParentCate()
      this.dialogCate=true
    },
    getCategories(){},
    //监听pagesize改变
    handleSizeChange(newPageSize){
      this.querInfo.pagesize=newPageSize
      this.cateList()
    },
    //监听pagenum改变
    handleCurrentChange(newPageNum){
      this.querInfo.pagenum=newPageNum
      this.cateList()
    },
    offForm(){
      this.dialogCate=false
    },
    sureForm(){
       this.dialogCate=false
       this.$refs.ruleForm.validate(async valid=>{
         if(!valid) return
         const {data:res}=await this.$http.post('categories',this.addCateForm)
         if(res.meta.status!==201){
           return this.$message.error('添加分类失败')
         }
         this.$message.success('添加分类成功')
         this.cateList()
       })
    },
    //获取父级分类的数据列表
    async getParentCate(){
      const {data:res}=await this.$http.get('categories',{params:{type:2}})
      if(res.meta.status!==200){
        return this.$message.error('获取父级分类数据失败')
      }
      this.parentCateList=res.data
    },
    handleChange(){
      console.log(this.selectKeys);
      // 判断
      if(this.selectKeys.length>0){
        this.addCateForm.cat_pid=this.selectKeys[this.selectKeys.length-1]
        this.addCateForm.cat_level=this.selectKeys.length
        return
      }else{
        this.addCateForm.cat_pid=0
        this.addCateForm.cat_level=0
      }
    },
    // 关闭在重新打开弹窗内容清空
    addCateDialog(){
      this.$refs.ruleForm.resetFields()
      this.selectKeys=[]
      this.addCateForm.cat_level=0
      this.addCateForm.cat_pid=0
    },
    async editCate(row){
     
      let id=row.cat_id
      const {data:res}=await this.$http.get(`categories/`+id)
      if(res.meta.status!==200) return this.$message.error('查询用户失败')
      this.editForm=res.data
      this.editDialogCate=true
    
    },
    editOffForm(){
      this.editDialogCate=false
    },
    editSureForm(){
      // 点击确定按钮验证输入框是否输入
        this.$refs.ruleFormEdit.validate(async valid=>{
          if(!valid) return
          // 发送添加请求
          const {data:res}=await this.$http.put(`categories/${this.editForm.cat_id}`,{cat_name:this.editForm.cat_name})
          
          if(res.meta.status!==200){
            this.$message.error('修改分类失败')
          }else{
             this.$message.success('修改分类成功')
             this.editDialogCate=false
            //  重新获取用户列表
           this.cateList()
          }
        })
    },
    removeCate(row){
       this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data:res }=await this.$http.delete(`categories/${row.cat_id}`)
          if(res.meta.status === 200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
         this.cateList()
          }
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  }
}
</script>

<style lang="less" scoped>
#categories{
  .box-card{
    margin: 20px 0;
    .search{
      .el-input-group{
        width: 20%;
      }
      .btn{
        margin-left: 25px;
      }
    }
    .tree-table{
      margin-top: 15px;
    }
  }
}
</style>